/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package trabalho2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;

/**
 *
 * @author rooke
 */
public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    public Principal() {
        
        Scanner scanner;
        try {
            
            scanner = new Scanner(new FileReader(DIR+"/lista_kth.txt")).useDelimiter("\\n");
        
            int i = 0;
            while (scanner.hasNext()) {
                nomes.add(i, scanner.next());
                i++;
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tiposEstrutura = new javax.swing.ButtonGroup();
        jFileChooser1 = new javax.swing.JFileChooser();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jPanel1 = new javax.swing.JPanel();
        radioLista = new javax.swing.JRadioButton();
        radioRTree = new javax.swing.JRadioButton();
        jPanel2 = new javax.swing.JPanel();
        btnSelecionarVideo = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        lbVideoSelecionado = new javax.swing.JLabel();
        btnBuscarVideos = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaResultados = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        textQtd = new javax.swing.JTextField();

        jScrollPane2.setViewportView(jTree1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Tipos de Estrutura"));

        tiposEstrutura.add(radioLista);
        radioLista.setText("Lista");
        radioLista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                habilitaSelecaoActionPerformed(evt);
            }
        });

        tiposEstrutura.add(radioRTree);
        radioRTree.setText("R*-Tree");
        radioRTree.setToolTipText("");
        radioRTree.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                habilitaSelecaoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(radioRTree)
                    .addComponent(radioLista))
                .addGap(0, 62, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(radioLista)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radioRTree)
                .addContainerGap(33, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Vídeo"));

        btnSelecionarVideo.setText("Selecionar Vídeo");
        btnSelecionarVideo.setEnabled(false);
        btnSelecionarVideo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSelecionarVideoActionPerformed(evt);
            }
        });

        jLabel1.setText("Vídeo Selecionado:");

        lbVideoSelecionado.setToolTipText("");
        lbVideoSelecionado.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSelecionarVideo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lbVideoSelecionado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(btnSelecionarVideo, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(lbVideoSelecionado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        btnBuscarVideos.setText("Buscar Vídeos Relacionados");
        btnBuscarVideos.setEnabled(false);
        btnBuscarVideos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarVideosActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Saídas"));

        areaResultados.setEditable(false);
        areaResultados.setBackground(new java.awt.Color(49, 32, 75));
        areaResultados.setColumns(20);
        areaResultados.setForeground(new java.awt.Color(254, 254, 254));
        areaResultados.setRows(5);
        jScrollPane1.setViewportView(areaResultados);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
        );

        jLabel2.setText("Qtd. Buscada:"); // NOI18N
        jLabel2.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        textQtd.setText("20");
        textQtd.setToolTipText("");
        textQtd.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(textQtd, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnBuscarVideos, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBuscarVideos, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(textQtd, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarVideosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarVideosActionPerformed
        
        
        if(radioLista.isSelected()){
                /*********************************/
                /*** Roda a estrutura de Lista ***/
                /*********************************/
                try {
                    areaResultados.append("[iniciando] busca com estrutura \"Lista...\"\n");
                    ///home/jayme/Documents/TrabalhoRIVideo/Trabalho2/VideoSearch /home/jayme/Documents/TrabalhoRIVideo/Trabalho2/Docs/Exemplo.fvec b 20
                    Process p = run.exec(DIR+"/VideoSearch "+DIR+"/Docs/Exemplo.fvec b "+textQtd.getText()+" "+DIR+"/Docs/descr.out");  
                    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
                    String retorno = "";
                    String line = null;  
                    while ((line = in.readLine()) != null) {  
                        
                        if(line.contains(">>")){
                            String indice = line.split(" ")[1];
                            areaResultados.append(nomes.get(Integer.parseInt(indice)-1)+" ");
                        }
                        
                        areaResultados.append(line+"\n");  
                    }
//                    while ((line = in.readLine()) != null) {  
//                        areaResultados.append(line+"\n");  
//                    }
                    p.waitFor();
                    areaResultados.append("[ok] busca finalizada. \n");
                } catch (Exception e){  
                    e.printStackTrace();  
                }  
                
                
        }else if(radioRTree.isSelected()){
                /**********************************/
                /*** Roda a estrutura de R-Tree ***/
                /**********************************/
                
                try {
                    areaResultados.append("[iniciando] busca com estrutura \"R*-Tree...\"\n");
                    
                    /*******************************************************/
                    /*** Mudar aqui em baixo o parametro de "b" para "r" ***/
                    /*******************************************************/
                    
                    Process p = run.exec(DIR+"/VideoSearch "+DIR+"/Docs/Exemplo.fvec r "+textQtd.getText()+" "+DIR+"/Docs/descr.out");  
                    BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));  
                    String retorno = "";
                    String line = null;  
                    while ((line = in.readLine()) != null) {  
                        
                        if(line.contains(">>")){
                            String indice = line.split(" ")[1];
                            areaResultados.append(nomes.get(Integer.parseInt(indice)-1)+" ");
                        }
                        
                        areaResultados.append(line+"\n");  
                    }
//                    while ((line = in.readLine()) != null) {  
//                        areaResultados.append(line+"\n");  
//                    }
                    p.waitFor();
                    areaResultados.append("[ok] busca finalizada. \n");
                } catch (Exception e){  
                    e.printStackTrace();  
                }  
                
            
            
            
        }
    }//GEN-LAST:event_btnBuscarVideosActionPerformed

    private void btnSelecionarVideoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarVideoActionPerformed
        run = Runtime.getRuntime();
        
        int returnVal = jFileChooser1.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            videoSelecionado = jFileChooser1.getSelectedFile();
            try {
                lbVideoSelecionado.setText(videoSelecionado.getAbsolutePath());
              
                areaResultados.append("[ok] vídeo "+videoSelecionado.getAbsolutePath()+" selecionado.\n");
                areaResultados.append("[iniciando] geração do vetor descritor do vídeo...\n");
                
                areaResultados.repaint();
                /********************************/
                /*** Gerar descritor do vídeo ***/
                /********************************/
                
                //Gera_vetor <caminhoVideo> 3 24 18 12 28 0.01 4 >descr.out


                Process process = run.exec("/bin/bash");
                OutputStream stdin = process.getOutputStream();
                InputStream stderr = process.getErrorStream();
                InputStream stdout = process.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));

                String input = DIR+"/Gera_vetor \""+videoSelecionado.getAbsolutePath()+"\" 3 24 18 12 28 0.01 4 >"+DIR+"/Docs/descr.out";
                input += "\n";
                writer.write(input);
                writer.flush();
                
                File file =  new File(DIR+"/Docs/descr.out");  
                while(!file.exists()) {  
                    // Aguarde 1 segundo  
                    Thread.sleep(1000);
                    areaResultados.append("Aguardando...\n");
                    
                    areaResultados.repaint();
                    
                    file = new File(DIR+"/Docs/descr.out");
                }  
                
                if(file.exists()) areaResultados.append("[ok] Arquivo descritor criado com sucesso...\n");
                
                
            } catch (Exception ex) {
              System.out.println("[erro] Problema ao carregar o \n");
            }
        } else {
            //System.out.println("File access cancelled by user.");
        }
        
        textQtd.setEnabled(true);
        btnSelecionarVideo.setEnabled(false);
        btnBuscarVideos.setEnabled(true);
    }//GEN-LAST:event_btnSelecionarVideoActionPerformed

    private void habilitaSelecaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_habilitaSelecaoActionPerformed
        
        if(radioLista.isSelected()){
                estrutura = "Lista";
                /*********************************/
                /*** Roda a estrutura de Lista ***/
                /*********************************/
                
                areaResultados.append("[ok] Estrutura \"Lista\" seleciionada.\n");
                
                
        }else if(radioRTree.isSelected()){
                estrutura = "R-Tree";
                /**********************************/
                /*** Roda a estrutura de R-Tree ***/
                /**********************************/
                areaResultados.append("[ok] Estrutura de \"R-Tree\" seleciionada.\n");
                
                
        }
        
        radioLista.setEnabled(false);
        radioRTree.setEnabled(false);
        btnSelecionarVideo.setEnabled(true);
        
    }//GEN-LAST:event_habilitaSelecaoActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea areaResultados;
    private javax.swing.JButton btnBuscarVideos;
    private javax.swing.JButton btnSelecionarVideo;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTree jTree1;
    private javax.swing.JLabel lbVideoSelecionado;
    private javax.swing.JRadioButton radioLista;
    private javax.swing.JRadioButton radioRTree;
    private javax.swing.JTextField textQtd;
    private javax.swing.ButtonGroup tiposEstrutura;
    // End of variables declaration//GEN-END:variables
    private File videoSelecionado;
    private String estrutura;
    private String DIR = System.getProperty("user.dir").replace(" ", "\\ ");
    private Runtime run;
    private ArrayList<String> nomes = new ArrayList<String>();
}
